#include <iostream>
#include "Acceptor.h"
#include "TcpConnection.h"
#include "EventLoop.h"
#include "TcpServer.h"
#include "ThreadPool.h"

#include <functional>

using std::bind;
using std::cout;
using std::endl;


using TcpConnectionPtr = shared_ptr<TcpConnection>;
using TcpConnectionCallback = function<void(const TcpConnectionPtr &)>;


ThreadPool *gPool;
class MyTask
{
public:
    MyTask(const string &msg, const TcpConnectionPtr &con)
    : _msg(msg)
    , _con(con)
    {

    }

    void process()
    {
        _con->sendInLoop(_msg);
    }
private:
    string _msg;
    TcpConnectionPtr _con;
};

void onNewConnection(const TcpConnectionPtr &con)
{
    con->toString();
    cout << " has connected." << endl;
}

void onMessage(const TcpConnectionPtr &con)
{
    string msg = con->receive();
    cout << ">>recv from client :" << msg << endl;

    MyTask task(msg, con);
    gPool->addTask(bind(&MyTask::process, task));
    /* con->send("i have received.\n"); */
}

void onClose(const TcpConnectionPtr &con)
{
    con->toString();
    cout << " has closed.." << endl;
}


void testV4()
{
    ThreadPool pool(5, 10);
    pool.start();
    gPool = &pool;
    TcpServer server("127.0.0.1", 8888);
    server.setAllCallback(std::move(onNewConnection), std::move(onMessage), std::move(onClose));
    server.start();
}

int main(int argc,char *argv[])
{
    testV4();
    return 0;
}


